<template>
  <div class="merchant-products">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </div>
      </template>
      
      <!-- 商品列表 -->
      <div class="card" style="margin-bottom: 5px">
        <div style="margin-bottom: 10px">
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </div>
        <el-table :data="data.tableData" stripe>
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" class="product-img" />
              <div v-else class="no-image">暂无图片</div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="productName"></el-table-column>
          <el-table-column label="商品价格" prop="price"></el-table-column>
          <el-table-column label="库存数量" prop="stock"></el-table-column>
          <el-table-column label="商品状态" prop="status">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
              <el-tag v-else type="danger">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row.productName)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="card">
        <el-pagination 
          background 
          layout="prev, pager, next" 
          :page-size="data.pageSize" 
          :current-page="data.pageNum"
          :total="data.total"
          @current-change="handleCurrentChange"
          :pager-count="5"
        />
      </div>
    </el-card>
    
    <!-- 订单管理 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
        </div>
      </template>
      
      <el-table :data="orderData.tableData" stripe>
        <el-table-column label="订单号" prop="orderNo"></el-table-column>
        <el-table-column label="商品信息">
          <template #default="scope">
            <div v-for="item in scope.row.orderItems" :key="item.orderItemId">
              {{ item.productName }} x {{ item.quantity }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总金额" prop="totalAmount"></el-table-column>
        <el-table-column label="下单时间">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1">待支付</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="success">已支付</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="warning">已发货</el-tag>
            <el-tag v-else-if="scope.row.status === 4" type="info">已完成</el-tag>
            <el-tag v-else type="danger">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 2" 
              type="primary" 
              @click="handleShip(scope.row)"
            >
              发货
            </el-button>
            <el-button 
              v-else-if="scope.row.status === 4" 
              type="success" 
              @click="viewOrderDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="card" style="margin-top: 15px;">
        <el-pagination 
          background 
          layout="prev, pager, next" 
          :page-size="orderData.pageSize" 
          :current-page="orderData.pageNum"
          :total="orderData.total"
          @current-change="handleOrderPageChange"
          :pager-count="5"
        />
      </div>
    </el-card>
    
    <!-- 商品编辑对话框 -->
    <el-dialog title="商品信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false">
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="data.form.productName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="data.form.category" placeholder="请选择">
            <el-option label="居家" value="居家"></el-option>
            <el-option label="美食" value="美食"></el-option>
            <el-option label="服饰" value="服饰"></el-option>
            <el-option label="运动" value="运动"></el-option>
            <el-option label="个护" value="个护"></el-option>
            <el-option label="严选" value="严选"></el-option>
            <el-option label="数码" value="数码"></el-option>
            <el-option label="car" value="car"></el-option>
            <el-option label="杂货" value="杂货"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="data.form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="data.form.stock" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="data.form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive, onMounted} from "vue";
import { useRouter } from "vue-router";
import {ElMessageBox, ElMessage} from "element-plus";
import { getMerchantOrders, merchantShipOrder } from "@/api";

const router = useRouter();

const data = reactive({
  pageNum: 1,           // 当前页码
  pageSize: 7,          // 每页条数，与后端默认值保持一致
  total: 0,             // 总条数
  formVisible: false,   // 表单弹窗显示状态
  form: {
    status: 1           // 默认商品状态：上架
  },
  tableData: [],        // 表格数据
  name: null            // 查询条件：商品名称
})

// 订单数据
const orderData = reactive({
  pageNum: 1,
  pageSize: 7,
  total: 0,
  tableData: []
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleString('zh-CN');
};

// 获取商品列表
const getProductList = () => {
  request.post("/home/merchant/findProducts", {
    page: data.pageNum - 1, // 注意：后端page从0开始，前端从1开始
    size: data.pageSize,
    name: data.name
  }).then(res => {
    if (res.success) {
      data.tableData = res.data;
      data.total = res.data ? res.data.length : 0;
    } else {
      ElMessage.error(res.message || "获取商品列表失败");
    }
  }).catch(err => {
    console.error("获取商品列表失败:", err);
    ElMessage.error("获取商品列表失败");
  });
};

// 获取订单列表
const getOrderList = async () => {
  try {
    const res = await getMerchantOrders();
    if (res.code === 200) {
      orderData.tableData = res.data;
      orderData.total = res.data ? res.data.length : 0;
    } else {
      ElMessage.error(res.message || "获取订单列表失败");
      orderData.tableData = [];
      orderData.total = 0;
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败");
    orderData.tableData = [];
    orderData.total = 0;
  }
};

// 处理分页变化
const handleCurrentChange = (val) => {
  data.pageNum = val;
  getProductList();
};

// 处理订单分页变化
const handleOrderPageChange = (val) => {
  orderData.pageNum = val;
  getOrderList();
};

// 处理新增商品
const handleAdd = () => {
  data.form = {
    status: 1
  };
  data.formVisible = true;
};

// 处理编辑商品
const handleEdit = (row) => {
  data.form = {...row};
  data.formVisible = true;
};

// 处理删除商品
const handleDelete = (name) => {
  ElMessageBox.confirm(`确定要删除商品"${name}"吗？`, "提示", {
    type: "warning"
  }).then(() => {
    request.post("/home/merchant/deleteProducts", {
      productName: name
    }).then(res => {
      if (res.success) {
        ElMessage.success("删除成功");
        getProductList();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    }).catch(err => {
      console.error("删除商品失败:", err);
      ElMessage.error("删除商品失败");
    });
  }).catch(() => {
    // 用户取消删除
  });
};

// 保存商品
const save = () => {
  if (!data.form.productName || !data.form.category || !data.form.price || !data.form.stock) {
    ElMessage.warning("请填写完整的商品信息");
    return;
  }

  const url = data.form.productId ? "/home/merchant/updateProducts" : "/home/merchant/addProductsWithImages";
  request.post(url, data.form).then(res => {
    if (res.success) {
      ElMessage.success(data.form.productId ? "更新成功" : "添加成功");
      data.formVisible = false;
      getProductList();
    } else {
      ElMessage.error(res.message || (data.form.productId ? "更新失败" : "添加失败"));
    }
  }).catch(err => {
    console.error("保存商品失败:", err);
    ElMessage.error("保存商品失败");
  });
};

// 处理发货
const handleShip = (order) => {
  ElMessageBox.confirm(`确定要为订单${order.orderNo}发货吗？`, "发货确认", {
    type: "warning"
  }).then(async () => {
    try {
      // 调用发货的API
      const res = await merchantShipOrder(order.orderId);
      if (res.code === 200 && res.data) {
        ElMessage.success("发货成功");
        // 更新订单状态
        order.status = 3;
        // 重新获取订单列表以更新状态
        await getOrderList();
      } else {
        ElMessage.error(res.message || "发货失败");
      }
    } catch (error) {
      console.error("发货失败:", error);
      ElMessage.error("发货失败，请稍后重试");
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 查看订单详情
const viewOrderDetail = (order) => {
  ElMessage.info(`查看订单详情，订单号：${order.orderNo}`);
  // 这里应该跳转到订单详情页面
};

onMounted(() => {
  getProductList();
  getOrderList();
});
</script>

<style scoped>
/* 整体布局 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  color: #333;
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 30px;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 5px;
}

/* 无图片占位符 */
.no-image {
  width: 80px;
  height: 80px;
  background: #f5f5f5;
  border: 1px dashed #ddd;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
  text-align: center;
}
</style>